package com.example.demo.controller;

import com.example.demo.config.AjaxResult;
import com.example.demo.model.*;
import com.example.demo.model.ProductInfo;
import com.example.demo.service.ProductService;
import com.example.demo.service.FileService;
import com.example.demo.util.ConstVariable;
import com.example.demo.vo.ProductVO;
import com.example.demo.service.AuctionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.math.BigDecimal;

import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.HashMap;

import java.text.SimpleDateFormat;
import java.text.ParseException;

import org.springframework.transaction.annotation.Transactional;


@RestController
@RequestMapping("/product")
@Slf4j
public class ProductController {
    @Autowired
    private ProductService productService;

    @Autowired
    private FileService fileService;

    @Autowired
    private AuctionService auctionService;

    @RequestMapping("/get-all")
    public List<ProductInfo> getAllProducts() {
        return productService.getAllProducts();
    }

    @RequestMapping("/choose")
    public Object productChoose(String brand, int minPrice, int maxPrice) {
        return productService.productChoose(brand, minPrice, maxPrice);
    }

    @RequestMapping("/detail")
    public AjaxResult getProductDetail(int id) {
        try {
            List<ProductVO> product = productService.getProductDetail(id);
            if (product == null) {
                return AjaxResult.fail("商品不存在");
            }
            // 增加浏览次数
            productService.incrementViewCount(id);
            return AjaxResult.success(product);
        } catch (Exception e) {
            log.error("获取商品详情失败", e);
            return AjaxResult.fail("获取商品详情失败");
        }
    }

    @PostMapping("/add")
    @Transactional
    public AjaxResult addProduct(@RequestBody Map<String, Object> productData, HttpSession session) {
        try {
            // 验证用户登录
            UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
            if (userInfo == null) {
                return AjaxResult.fail("请先登录");
            }

            // 创建商品基本信息
            ProductInfo product = new ProductInfo();
            product.setName((String) productData.get("name"));
            product.setPrice(new BigDecimal(productData.get("price").toString()));
            product.setOriginalPrice(productData.get("originalPrice") != null ? 
                new BigDecimal(productData.get("originalPrice").toString()) : null);
            product.setShippingFee(new BigDecimal(productData.get("shippingFee").toString()).intValue());
            product.setBrand((String) productData.get("brand"));
            product.setCategoryId((Integer) productData.get("categoryId"));
            product.setCategoryPath((String) productData.get("categoryPath"));
            product.setConditionLevel((Integer) productData.get("conditionLevel"));
            product.setDescription((String) productData.get("description"));
            product.setImages((String) productData.get("images"));
            product.setLocation((String) productData.get("location"));
            product.setIsAuction((Integer) productData.get("isAuction"));
            product.setSellerId(userInfo.getId());
            
            // 设置默认值
            product.setStatus(1);
            product.setViewCount(0);
            product.setFavoriteCount(0);
            product.setCreateTime(new Date());
            product.setUpdateTime(new Date());

            // 保存商品信息
            boolean success = productService.createProduct(product);
            if (!success) {
                return AjaxResult.fail("商品创建失败");
            }

            // 如果是拍卖商品，创建拍卖信息
            if (product.getIsAuction() == 1) {
                @SuppressWarnings("unchecked")
                Map<String, Object> auctionInfo = (Map<String, Object>) productData.get("auctionInfo");
                
                AuctionInfo auction = new AuctionInfo();
                auction.setProductId(product.getId().longValue());
                auction.setStartPrice(new BigDecimal(auctionInfo.get("startPrice").toString()));
                auction.setCurrentPrice(auction.getStartPrice());
                auction.setMinIncrement(new BigDecimal(auctionInfo.get("minIncrement").toString()));
                auction.setStartTime(parseDateTime((String) auctionInfo.get("startTime")));
                auction.setEndTime(parseDateTime((String) auctionInfo.get("endTime")));
                auction.setStatus(0);

                if (!auctionService.createAuction(auction)) {
                    throw new RuntimeException("拍卖信息创建失败");  // 抛出异常以触发事务回滚
                }
            }

            return AjaxResult.success("发布成功");
        } catch (Exception e) {
            log.error("发布商品失败", e);
            return AjaxResult.fail("发布失败：" + e.getMessage());
        }
    }

    private Date parseDateTime(String dateTimeStr) {
        try {
            return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm").parse(dateTimeStr);
        } catch (ParseException e) {
            throw new RuntimeException("日期格式错误");
        }
    }

//    @RequestMapping("/update-status")
//    public AjaxResult updateStatus(int id, int status, HttpSession session) {
//        try {
//            UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
//            if (userInfo == null) {
//                return AjaxResult.fail("请先登录");
//            }
//
//            boolean success = productService.updateStatus(id, status, userInfo.getId());
//            return success ? AjaxResult.success("更新成功") : AjaxResult.fail("更新失败");
//        } catch (Exception e) {
//            log.error("更新商品状态失败", e);
//            return AjaxResult.fail("更新失败");
//        }
//    }



    @GetMapping("/recommended")
    public AjaxResult getRecommendedProducts(@RequestParam(defaultValue = "100") int limit) {
        try {
            List<ProductVO> products = productService.getProductsByViewCount(limit);
            return AjaxResult.success(products);
        } catch (Exception e) {
            log.error("获取推荐商品失败", e);
            return AjaxResult.fail("获取推荐商品失败");
        }
    }

    @GetMapping("/filter")
    public AjaxResult filterProducts(
            @RequestParam(required = false) String categoryPath,
            @RequestParam(required = false) Integer condition,
            @RequestParam(required = false) BigDecimal minPrice,
            @RequestParam(required = false) BigDecimal maxPrice,
            @RequestParam(required = false, defaultValue = "default") String sort) {
        try {
            log.info("过滤商品 - categoryPath: {}, condition: {}, minPrice: {}, maxPrice: {}, sort: {}", 
                    categoryPath, condition, minPrice, maxPrice, sort);

            // 构建过滤参数
            Map<String, Object> params = new HashMap<>();
            params.put("categoryPath", categoryPath); // 直接传入完整的分类路径
            params.put("condition", condition);
            params.put("minPrice", minPrice);
            params.put("maxPrice", maxPrice);
            params.put("sort", sort);

            List<ProductInfo> products = productService.filterProducts(params);
            return AjaxResult.success(products);
        } catch (Exception e) {
            log.error("过滤商品失败", e);
            return AjaxResult.fail("过滤商品失败");
        }
    }




}
